package handler

import (
	"api-getway/internal/resp"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/minio/minio-go/v7"
	"github.com/minio/minio-go/v7/pkg/credentials"
	"net/http"
	"path/filepath"
)

const endpoint = "117.27.231.169:9000"
const accessKeyID = "ebWNX8Kf32zaiPk3FHDx"
const secretAccessKey = "cHKJkS5Jql5MTliNoJDtSBEpqQqf7j6Pc23cMalX"
const bucketName = "lbb"

func Upload(c *gin.Context) {

	file, _ := c.FormFile("file")
	open, err := file.Open()
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error:": "文件获取失败"})
		return
	}
	if file.Size > 3*1024*1024 {
		c.JSON(http.StatusBadRequest, gin.H{"error:": "图片过大"})
		return
	}
	filename := file.Filename
	ext := filepath.Ext(filename)

	m := map[string]bool{
		".png": true,
	}
	if !m[ext] {
		c.JSON(http.StatusBadRequest, gin.H{"error:": "图片格式错误"})
		return
	}
	minioClient, err := minio.New(endpoint, &minio.Options{
		Creds: credentials.NewStaticV4(accessKeyID, secretAccessKey, ""),
	})
	if err != nil {
		return
	}
	objectName := file.Filename
	_, err = minioClient.PutObject(c, bucketName, objectName, open, file.Size, minio.PutObjectOptions{ContentType: ""})
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error:": "文件上传失败"})
		return
	}
	url := fmt.Sprintf("http://%s/%s/%s", endpoint, bucketName, objectName)
	c.JSON(http.StatusOK, resp.Res{
		Code: 200,
		Msg:  "上传成功",
		Data: map[string]interface{}{"url": url},
	})

}
